<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-row class="demo-autocomplete" style="margin-bottom: 20px">
      <!-- 添加商品 -->
      <el-col style="width: 10%; float: left">
        <el-button type="primary" @click="addProduct">添加商品</el-button>
      </el-col>
      <!-- 搜索框 -->
      <el-col style="width: 90%; float: left">
        <el-input
          @input="searchProduct(input1)"
          v-model="input1"
          style="width: 20%; margin-left: 25px"
          placeholder="请输入商品ID"
        ></el-input>
        <el-button
          plain
          type="info"
          style="margin-left: 10px"
          @click="searchProduct(input1)"
          >搜索 ID</el-button
        >
        <el-input
          @input="searchProductByName(input2)"
          v-model="input2"
          style="width: 20%; margin-left: 25px"
          placeholder="请输入商品名称"
        ></el-input>
        <el-button
          plain
          type="info"
          style="margin-left: 10px"
          @click="searchProductByName(input2)"
          >搜索名称</el-button
        >
        <el-input
          v-model="input3"
          @input="searchProductByDesc(input3)"
          style="width: 20%; margin-left: 25px"
          placeholder="请输入商品描述"
        ></el-input>
        <el-button
          plain
          type="info"
          style="margin-left: 10px"
          @click="searchProductByDesc(input3)"
          >搜索描述</el-button
        >
      </el-col>
    </el-row>
    <!-- 发布商品表单 -->
    <el-dialog title="添加商品" :visible.sync="dialogVisibleadd" width="60%">
      <el-form ref="newProduct" :model="newProduct" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="newProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newProduct.descriptions"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="newProduct.quantity"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="newProduct.content"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="newProduct.price"></el-input>
        </el-form-item>
        <el-form-item label="主图">
          <el-upload
            class="avatar-uploader"
            action="http://lanlianhua.work:8888/api/v1/common/file_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imgUrl"
              :src="imgUrl"
              class="img"
              width="100"
              height="100"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleadd = false">取 消</el-button>
        <el-button type="primary" @click="addSure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 搜索结果展示 -->
    <el-table :data="selectProduct" v-show="flag" border style="width: 100%">
      <el-table-column prop="_id" label="商品id"> </el-table-column>
      <el-table-column prop="name" label="标题"> </el-table-column>
      <el-table-column prop="price" label="价格"> </el-table-column>
      <el-table-column prop="quantity" label="库存数量"> </el-table-column>
      <el-table-column prop="coverImg" label="主图">
        <!-- 作用域插槽 -->
        <template slot-scope="scope">
          <img
            :src="scope.row.coverImg | handleImgPath"
            width="100"
            height="100"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <!-- scope.row 获取当前这条数据 -->
          <el-button @click="editProduct(scope.row)" type="primary" size="small"
            >修改</el-button
          >
          <el-popconfirm
            title="确定删除这条商品数据吗？"
            @onConfirm="delProduct(scope.row)"
          >
            <el-button type="danger" size="small" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 商品列表 -->
    <el-table
      :data="
        tableData.slice((currentPage - 1) * PageSize, currentPage * PageSize)
      "
      v-show="!flag"
      border
      style="width: 100%"
    >
      <el-table-column prop="_id" label="商品id"> </el-table-column>
      <el-table-column prop="name" label="标题"> </el-table-column>
      <el-table-column prop="price" label="价格"> </el-table-column>
      <el-table-column prop="quantity" label="库存数量"> </el-table-column>
      <el-table-column prop="coverImg" label="主图">
        <!-- 作用域插槽 -->
        <template slot-scope="scope">
          <img
            :src="scope.row.coverImg | handleImgPath"
            width="100"
            height="100"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <!-- scope.row 获取当前这条数据 -->
          <el-button @click="editProduct(scope.row)" type="primary" size="small"
            >修改</el-button
          >
          <el-popconfirm
            title="确定删除这条商品数据吗？"
            @onConfirm="delProduct(scope.row)"
          >
            <el-button type="danger" size="small" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改商品信息  -->
    <el-dialog
      title="修改商品信息"
      :visible.sync="dialogVisibleedit"
      width="60%"
    >
      <el-form ref="product" v-model="product" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="product.name"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="product.price"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="product.quantity"></el-input>
        </el-form-item>
        <el-form-item label="主图">
          <el-upload
            class="avatar-uploader"
            action="http://lanlianhua.work:8888/api/v1/common/file_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="img"
              width="100"
              height="100"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleedit = false">取 消</el-button>
        <el-button type="primary" @click="editSure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      background
      v-show="!flag"
      style="margin-top: 20px; margin-bottom: 50px"
      layout=" prev, pager, next, jumper"
      :total="totalCount"
      :page-size="PageSize"
      :page-sizes="PageSizes"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  getProducts,
  getPerProduct,
  jiaProduct,
  xiugaiProduct,
  deleteProduct,
} from "../../api/product";
export default {
  name: "ProductList",
  components: {},
  data() {
    return {
      restaurants: [],
      tableData: [],
      dialogVisibleadd: false,
      dialogVisibleedit: false,
      imageUrl: "",
      imgUrl: "",
      product: {
        name: "",
        price: "",
        quantity: "",
      },
      newProduct: {},
      selectProduct: [],
      currentPage: 1,
      totalCount: 0,
      PageSize: 10,
      PageSizes: [10, 20, 30],
      flag: false,
      id: "",
      input1: "",
      input2: "",
      input3: "",
    };
  },
  mounted() {},
  filters: {
    handleImgPath(str) {
      if (str) {
        if (str.startsWith("http") || str.startsWith("data")) {
          return str;
        } else {
          return "http://lanlianhua.work:8888" + str;
        }
      } else {
        return "http://www.superslide2.com/demo/images/pic3.jpg";
      }
    },
  },
  computed: {
    searchInput1() {
      return this.input1;
    },
    searchInput2() {
      return this.input2;
    },
    searchInput3() {
      return this.input3;
    },
  },
  watch: {
    searchInput1(newVal, oldVal) {
      if (newVal === "") {
        this.flag = false;
        this.initProducts(); //加载商品列表
      }
    },
    searchInput2(newVal, oldVal) {
      if (newVal === "") {
        this.flag = false;
        this.initProducts(); //加载商品列表
      }
    },
    searchInput3(newVal, oldVal) {
      if (newVal === "") {
        this.flag = false;
        this.initProducts(); //加载商品列表
      }
    },
  },
  created() {
    this.initProducts();
  },

  methods: {
    //通过id查询单个商品
    async searchProduct(id) {
      if (id) {
        const result = await getPerProduct(id);
        console.log(result);
        this.selectProduct.push(result);
        console.log(this.selectProduct);
        this.flag = true;
      } else {
        this.selectProduct = [];
        this.flag = false;
        this.initProducts();
      }
    },
    //通过名称查询商品
    searchProductByName(nameStr) {
      // console.log(this.input2);
      this.tableData.forEach((item) => {
        console.log(item.name);
        if (item.name.includes(nameStr)) {
          this.id = item._id;
          this.searchProduct(this.id);
        }
      });
    },
    //通过描述查询商品
    searchProductByDesc(descStr) {
      // console.log(this.input2);
      this.tableData.forEach((item) => {
        console.log(item.descriptions);
        if (item.descriptions.includes(descStr)) {
          this.id = item._id;
          this.searchProduct(this.id);
        }
      });
    },

    //获取商品列表
    async initProducts(per, page) {
      const result = await getProducts(10, 1);
      console.log(111, result);
      this.tableData = result.products;
      // console.log(this.tableData);
      this.totalCount = result.totalCount;
    },

    //分页
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize = val;
      // 点击每页显示的条数时，显示第一页
      this.initProducts(val, 1);
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.currentPage = 1;
    },
    // // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.currentPage = val;
      // 切换页码时，要获取每页显示的条数
      this.initProducts(this.PageSize, val);
    },

    //新增商品
    addProduct() {
      this.dialogVisibleadd = true;
    },
    //确定新增
    async addSure() {
      const result = await jiaProduct({
        name: this.newProduct.name,
        descriptions: this.newProduct.descriptions,
        quantity: this.newProduct.quantity,
        content: this.newProduct.content,
        price: this.newProduct.price,
        coverImg: this.imgUrl,
        productCategory: this.newProduct.id,
      });
      console.log("添加成功", result);
      this.dialogVisibleadd = false; // 关闭弹框
      this.initProducts(); // 再次调用接口
    },
    //上传主图
    handleAvatarSuccess(res, file) {
      // console.log(res);
      // console.log(file);
      this.imageUrl = "http://lanlianhua.work:8888" + res.info;
      this.imgUrl = "http://lanlianhua.work:8888" + res.info;
      console.log(this.imageUrl);
    },
    //过滤头像
    handleImgPath(str) {
      if (str) {
        if (str.startsWith("http") || str.startsWith("data")) {
          return str;
        } else {
          return "http://lanlianhua.work:8888" + str;
        }
      } else {
        return "http://www.superslide2.com/demo/images/pic3.jpg";
      }
    },
    //弹出修改弹窗
    editProduct(product) {
      this.dialogVisibleedit = true; //打开弹框
      //数据回显
      this.product.name = product.name;
      this.product.price = product.price;
      this.product.quantity = product.quantity;
      this.imageUrl = this.handleImgPath(product.coverImg);
      this.product.id = product._id;
      console.log(this.imageUrl);
    },
    //确定修改
    async editSure() {
      const result = await xiugaiProduct(this.product.id, {
        name: this.product.name,
        price: this.product.price,
        quantity: this.product.quantity,
        coverImg: this.imageUrl,
      });
      // console.log("修改成功", result);
      console.log(this.imageUrl, "ddd");
      this.dialogVisibleedit = false; // 关闭弹框
      this.initProducts(); // 再次调用接口显示商品列表
    },
    //删除
    async delProduct(product) {
      const result = await deleteProduct(product._id);
      if (result.code === 20000) {
        console.log("删除成功", result);
        this.initProducts(); // 再次调用接口
      } else {
        console.log(result.error);
      }
    },
    //判断上传的文件是否符合下面的规范
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped>
/* .addGood {
  margin-bottom: 20px;
  width: 20%;
} */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
